<?php defined('SYSPATH') or die('No direct script access.');

/**
 * 对账记录
 * Class Controller_Admin_Finance_Record_Check
 */
class Controller_Admin_Finance_Record_Check extends Stourweb_Controller
{
    public function before()
    {


        $this->assign('prefix_url','finance/admin/finance/record');
        parent::before();
    }

    public function action_index()
    {
        $action = $this->params['action'];
        if (empty($action))
        {
            $moduels =  DB::select('id', 'modulename', 'pinyin','maintable','correct')
                ->from('model')
                ->where('is_orderable', '=', 1)
                ->execute()
                ->as_array();
            $user_id = Session::instance()->get('userid');
            $config_file = CACHE_DIR . 'newtravel/menu_' . $user_id . '.php';
            $memu=require $config_file;
            $temp=array();
            foreach($memu as $item)
            {
                if(!empty($item["url"]) && preg_match('~order/index~is',$item["url"]))
                {
                    $temp[$item["typeid"]]=$item["id"];
                }
            }
            foreach($moduels as &$item)
            {
                if(isset($temp[$item['id']]))
                {
                    $item['menuid']=$temp[$item['id']];
                }
            }
            $channel_list = St_Functions::get_ota_channel(null,true);

            $this->assign('channel_list', $channel_list);
            $this->assign('modules',$moduels);
            $this->display('admin/finance/record/index');
        }
        else if ($action == 'read')    //读取列表
        {
            $start = Arr::get($_GET, 'start');
            $limit = Arr::get($_GET, 'limit');
            $type = Arr::get($_GET,'type');
            $startdate = Arr::get($_GET,'startdate');
            $enddate = Arr::get($_GET,'enddate');
            $modules_id = Arr::get($_GET,'modules_id');
            $channel_id = Arr::get($_GET,'channel_id');
            $w = " where a.id >0 ";
            if($type)
            {
                $w .= " and a.type =".$type;
            }
            if($modules_id){
                $w .= " and mo.typeid =".$modules_id;
            }
            //时间
            if($startdate)
            {
                $w .=" and a.addtime >".strtotime($startdate);
            }
            if($enddate)
            {
                $w .=" and a.addtime <=".strtotime($enddate);
            }
            if($channel_id){
                $w .= " and mo.channel_id={$channel_id} ";
            }
            $sql = "select a.* from  `sline_finance_record` a join sline_member_order as mo on mo.ordersn = a.ordersn $w order by a.addtime desc ";
            $sql.= "limit {$start},{$limit}";
            $totalcount_arr = DB::query(Database::SELECT, "select count(a.id) as num from  `sline_finance_record` a join sline_member_order as mo on mo.ordersn = a.ordersn $w ")->execute()->as_array();
            $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
            foreach($list as &$row)
            {
                if($row['ordersn'])
                {
                    $order = DB::select()->from('member_order')
                        ->where('ordersn','=',$row['ordersn'])
                        ->execute()
                        ->current();
                    $row['order_id'] = $order['id'];
                    $row['typeid'] = $order['typeid'];
                    $row['channel_name'] = DB::select('modulename')->from('model')
                        ->where('id','=',$order['typeid'])
                        ->execute()
                        ->get('modulename');

                }
                if($row['type']==2){
                    $refund_fee = DB::select('refund_fee')->from('member_order_refund')
                        ->where('ordersn','=',$row['ordersn'])
                        ->execute()
                        ->current();
                    $row['remark'] = "订单{$row['ordersn']}成功支出{$refund_fee['refund_fee']}";
                }
            }
            $result['total'] = $totalcount_arr[0]['num'];
            $result['lists'] = $list;
            $result['success'] = true;
            echo json_encode($result);
        }
        else if ($action == 'save')   //保存字段
        {
        }
        else if ($action == 'delete') //删除某个记录
        {

        }
        else if ($action == 'update')//更新某个字段
        {

        }

    }


    /*
   * 生成excel页面
   * */
    public function action_excel()
    {
        $this->assign('params',$_GET);
        $this->display('admin/finance/record/excel');
    }

    public function action_genexcel()
    {
        $timetype = $this->params['timetype'];
        $starttime = empty($_GET['starttime'])? null:strtotime($_GET['starttime'].' 00:00:00');
        $endtime =empty($_GET['endtime'])?null: strtotime($_GET['endtime'].' 23:59:59');
        $time_arr = array();
        switch ($timetype)
        {
            case 1:
                $time_arr = St_Functions::back_get_time_range(1);
                break;
            case 2:
                $time_arr = St_Functions::back_get_time_range(2);
                break;
            case 3:
                $time_arr = St_Functions::back_get_time_range(3);
                break;
            case 5:
                $time_arr = St_Functions::back_get_time_range(5);
                break;
            case 6:
                $time_arr = array($starttime, $endtime);
                break;
        }

        $w = " where a.id >0 ";
        //开始结束时间
        $w  .= " and a.addtime > $time_arr[0] and  a.addtime < $time_arr[1] " ;
        $sql = "select a.*  from `sline_finance_record` a $w   order by a.addtime desc ";
        $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
        $this->gene_excel($list);

    }

    /**
     * 生成excel
     * @param $records
     * @return string
     */
    protected function gene_excel($records)
    {
        $titles = array('时间','金额','收支','收支类型','订单号','备注');
        $rows = array();
        foreach ($records as $row)
        {

            $type = $row['type'] == 1 ? '收入' : '支出';
            $ordersn = $row['ordersn'] ? $row['ordersn'] : '-';
            $rows[] = array(
                date('Y-m-d H:i:s',$row['addtime']),
                $row['amount'],
                $type,
                $row['type_desc'],
                $ordersn,
                $row['remark']

            );

        }
        $td_width = array(25,20,15,15,25,40);
        $col_style = array('string','string','string','string','string','string');
        St_File::export_excel($rows, $titles, $td_width, $col_style);

    }



}